<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta http-equiv="Cache-Control" content="no-siteapp">
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
  <meta name="renderer" content="webkit">

  
  <title>Android 10.0 Launcher 启动流程 | 龙之叶的博客</title>

  <link rel="shortcut icon" href="/images/favicon.png">
  <link rel="alternate" href="/atom.xml" title="龙之叶的博客" type="application/atom+xml">
  <meta name="description" content="Android 10.0 Launcher 启动流程">
<meta property="og:type" content="article">
<meta property="og:title" content="Android 10.0 Launcher 启动流程">
<meta property="og:url" content="http://longzhiye.top/2023/11/25/2023-11-25/index.html">
<meta property="og:site_name" content="龙之叶的博客">
<meta property="og:description" content="Android 10.0 Launcher 启动流程">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://longzhiye.top/images/20231125/20231125001.jpg">
<meta property="og:image" content="http://longzhiye.top/images/20231125/20231125002.jpg">
<meta property="og:image" content="http://longzhiye.top/images/20231125/20231125003.jpg">
<meta property="og:image" content="http://longzhiye.top/images/20231125/20231125004.jpg">
<meta property="article:published_time" content="2023-11-24T16:00:00.000Z">
<meta property="article:modified_time" content="2024-08-29T02:40:34.913Z">
<meta property="article:author" content="龙之叶">
<meta property="article:tag" content="Android">
<meta property="article:tag" content="framework">
<meta property="article:tag" content="Launcher">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://longzhiye.top/images/20231125/20231125001.jpg">

  <meta name="keywords" content=",Android,framework,Launcher">
  <meta name="format-detection" content="telephone=no,email=no">
  <meta name="theme-color" content="#9C27B0">

  <meta name="mobile-web-app-capable" content="yes">
  <meta name="application-name" content="龙之叶的博客">
  <meta name="msapplication-starturl" content="http://longzhiye.top/2023/11/25/2023-11-25/">
  <meta name="msapplication-navbutton-color" content="#9C27B0">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-title" content="龙之叶的博客">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <link rel="apple-touch-icon" href="/images/favicon.png">

  
    <link rel="canonical" href="http://longzhiye.top/2023/11/25/2023-11-25/">
  

  
  

  
  
  

  
<link rel="stylesheet" href="/css/mdui.css">
<link rel="stylesheet" href="/css/style.css">

  
<link rel="stylesheet" href="/custom.css">

<meta name="generator" content="Hexo 5.4.2"></head>

<body class="mdui-appbar-with-toolbar mdui-theme-primary-indigo mdui-theme-accent-pink">
  <script>var a=localStorage.getItem("mdui-theme-layout-dark");if(a){document.getElementsByTagName("body")[0].className+=" mdui-theme-layout-dark"};</script>
  <script>if(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches){document.getElementsByTagName("body")[0].className+=" mdui-theme-layout-dark"};</script>
  <script>var a=localStorage.getItem("mdui-drawer-close");if(!a){document.getElementsByTagName("body")[0].className+=" mdui-drawer-body-left"};</script>
  <header id="header" class="mdui-appbar mdui-appbar-fixed mdui-appbar-scroll-hide mdui-appbar-inset">
  <div class="mdui-toolbar mdui-color-theme">
    <a href="javascript:;" class="mdui-btn mdui-btn-icon" mdui-drawer="{target: '#sidebar', swipe: true}"><i class="mdui-icon material-icons">menu</i></a>
    <a href="/" class="mdui-typo-headline">龙之叶的博客</a>
    <div class="mdui-toolbar-spacer"></div>
    <a href="javascript:;" class="mdui-btn mdui-btn-icon" mdui-dialog="{target: '#search'}" mdui-tooltip="{content: '搜索'}"><i class="mdui-icon material-icons">search</i></a>
	<!--
    <a href="/atom.xml" class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: 'RSS'}"><i class="mdui-icon material-icons">rss_feed</i></a>
	-->
  </div>
</header>
<div class="mdui-dialog" id="search">
  
    <div class="search-form">
      <input type="search" class="search-form-input" placeholder="请输入关键字">
    </div>
    <div class="search-result" data-resource="/search.xml"></div>
  
</div>

  <aside id="sidebar" class="mdui-drawer mdui-drawer-full-height">
  <script>var a=localStorage.getItem("mdui-drawer-close");if(a){document.getElementById("sidebar").className+=" mdui-drawer-close"};</script>
  <div class="mdui-grid-tile">
    <img src="/images/banner.png" style="height: 160px;">
    <img src="/images/avatar.png" class="avatar-animation" style="position: absolute; top: 10%; left: 24px; width: 64px; height: 64px; border: 2px solid #fff; border-radius: 50%;background-color:#fff;">
    <div class="mdui-grid-tile-actions">
      <div class="mdui-grid-tile-text">
        <div class="mdui-grid-tile-title">龙之叶</div>
        <div class="mdui-grid-tile-subtitle"><i class="mdui-icon material-icons">art_track</i>生命不息，折腾不止</div>
      </div>
      
        <div class="mdui-grid-tile-buttons">
          <a href="mailto:longzhiye163@163.com" class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: 'longzhiye163@163.com'}"><i class="mdui-icon material-icons">email</i></a>
        </div>
      
    </div>
  </div>

  <div class="mdui-list" mdui-collapse="{accordion: true}">
    <a href="/" class="mdui-list-item mdui-ripple">
      <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-blue">home</i>
      <div class="mdui-list-item-content">主页</div>
    </a>
    <div class="mdui-collapse-item">
      <script>var a=localStorage.getItem("mdui-collapse-item-0");if(a){document.getElementsByClassName("mdui-collapse-item")[0].className+=" mdui-collapse-item-open"};</script>
      <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
        <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-deep-orange">archive</i>
        <div class="mdui-list-item-content">归档</div>
        <i class="mdui-collapse-item-arrow mdui-icon material-icons">keyboard_arrow_down</i>
      </div>
      <div class="mdui-collapse-item-body mdui-list mdui-list-dense">
        
        <a class="mdui-ripple sidebar_archives-link" href="/archives/2025/07/">七月 2025<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2025/06/">六月 2025<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2025/03/">三月 2025<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2025/02/">二月 2025<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2025/01/">一月 2025<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2024/10/">十月 2024<span class="mdui-ripple sidebar_archives-count">7</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2024/09/">九月 2024<span class="mdui-ripple sidebar_archives-count">4</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2024/08/">八月 2024<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2024/03/">三月 2024<span class="mdui-ripple sidebar_archives-count">5</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2024/02/">二月 2024<span class="mdui-ripple sidebar_archives-count">11</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2024/01/">一月 2024<span class="mdui-ripple sidebar_archives-count">9</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/12/">十二月 2023<span class="mdui-ripple sidebar_archives-count">10</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/11/">十一月 2023<span class="mdui-ripple sidebar_archives-count">8</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/10/">十月 2023<span class="mdui-ripple sidebar_archives-count">8</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/09/">九月 2023<span class="mdui-ripple sidebar_archives-count">3</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/08/">八月 2023<span class="mdui-ripple sidebar_archives-count">6</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/06/">六月 2023<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/05/">五月 2023<span class="mdui-ripple sidebar_archives-count">4</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/04/">四月 2023<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/03/">三月 2023<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2023/02/">二月 2023<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2022/09/">九月 2022<span class="mdui-ripple sidebar_archives-count">7</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2022/08/">八月 2022<span class="mdui-ripple sidebar_archives-count">4</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2017/04/">四月 2017<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2017/03/">三月 2017<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2017/02/">二月 2017<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2017/01/">一月 2017<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2016/12/">十二月 2016<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2016/11/">十一月 2016<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2016/10/">十月 2016<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/archives/2016/08/">八月 2016<span class="mdui-ripple sidebar_archives-count">1</span></a>
        
      </div>
    </div>
    <div class="mdui-collapse-item">
      <script>var a=localStorage.getItem("mdui-collapse-item-1");if(a){document.getElementsByClassName("mdui-collapse-item")[1].className+=" mdui-collapse-item-open"};</script>
      <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
        <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-green">class</i>
        <div class="mdui-list-item-content">分类</div>
        <i class="mdui-collapse-item-arrow mdui-icon material-icons">keyboard_arrow_down</i>
      </div>
      <div class="mdui-collapse-item-body mdui-list mdui-list-dense">
        
        <a class="mdui-ripple sidebar_archives-link" href="/categories/%E6%8A%80%E6%9C%AF/">技术<span class="mdui-ripple sidebar_archives-count">98</span></a><a class="mdui-ripple sidebar_archives-link" href="/categories/%E7%94%9F%E6%B4%BB/">生活<span class="mdui-ripple sidebar_archives-count">3</span></a><a class="mdui-ripple sidebar_archives-link" href="/categories/%E8%B5%84%E8%AE%AF/">资讯<span class="mdui-ripple sidebar_archives-count">4</span></a><a class="mdui-ripple sidebar_archives-link" href="/categories/%E9%80%9A%E7%9F%A5/">通知<span class="mdui-ripple sidebar_archives-count">4</span></a>
        
      </div>
    </div>
    <div class="mdui-collapse-item">
      <script>var a=localStorage.getItem("mdui-collapse-item-2");if(a){document.getElementsByClassName("mdui-collapse-item")[2].className+=" mdui-collapse-item-open"};</script>
      <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
        <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-brown">bookmark</i>
        <div class="mdui-list-item-content">标签</div>
        <i class="mdui-collapse-item-arrow mdui-icon material-icons">keyboard_arrow_down</i>
      </div>
      <div class="mdui-collapse-item-body mdui-list mdui-list-dense">
        
        <a class="mdui-ripple sidebar_archives-link" href="/tags/ANR/" rel="tag">ANR<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/APP/" rel="tag">APP<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Android/" rel="tag">Android<span class="mdui-ripple sidebar_archives-count">89</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Android12/" rel="tag">Android12<span class="mdui-ripple sidebar_archives-count">3</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Android13/" rel="tag">Android13<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Android14/" rel="tag">Android14<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/AndroidStudio/" rel="tag">AndroidStudio<span class="mdui-ripple sidebar_archives-count">3</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/AutoDraw/" rel="tag">AutoDraw<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Crash/" rel="tag">Crash<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Foxmail/" rel="tag">Foxmail<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Framework/" rel="tag">Framework<span class="mdui-ripple sidebar_archives-count">20</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/GPS%E8%BD%A8%E8%BF%B9%E5%9B%BE/" rel="tag">GPS轨迹图<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Git/" rel="tag">Git<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/GitHub/" rel="tag">GitHub<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Google/" rel="tag">Google<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Hexo/" rel="tag">Hexo<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Java/" rel="tag">Java<span class="mdui-ripple sidebar_archives-count">3</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Kernel/" rel="tag">Kernel<span class="mdui-ripple sidebar_archives-count">4</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Launcher/" rel="tag">Launcher<span class="mdui-ripple sidebar_archives-count">17</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Lib/" rel="tag">Lib<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Linux/" rel="tag">Linux<span class="mdui-ripple sidebar_archives-count">18</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Markdown/" rel="tag">Markdown<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Material-Design/" rel="tag">Material Design<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/OS-X/" rel="tag">OS X<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/OTA/" rel="tag">OTA<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/QuickTime/" rel="tag">QuickTime<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/SSH/" rel="tag">SSH<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Settings/" rel="tag">Settings<span class="mdui-ripple sidebar_archives-count">6</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/SystemUI/" rel="tag">SystemUI<span class="mdui-ripple sidebar_archives-count">19</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Ubuntu/" rel="tag">Ubuntu<span class="mdui-ripple sidebar_archives-count">7</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/WPS/" rel="tag">WPS<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Wifi/" rel="tag">Wifi<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/WindTerm/" rel="tag">WindTerm<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/Windows/" rel="tag">Windows<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/androidmk/" rel="tag">androidmk<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/blog/" rel="tag">blog<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/build/" rel="tag">build<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/feel/" rel="tag">feel<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/framework/" rel="tag">framework<span class="mdui-ripple sidebar_archives-count">50</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/git/" rel="tag">git<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/inotify/" rel="tag">inotify<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/life/" rel="tag">life<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/ninja/" rel="tag">ninja<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/rsync/" rel="tag">rsync<span class="mdui-ripple sidebar_archives-count">2</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/standard/" rel="tag">standard<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/test/" rel="tag">test<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1/" rel="tag">企业微信<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" rel="tag">操作系统<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/%E6%B5%8B%E8%AF%95/" rel="tag">测试<span class="mdui-ripple sidebar_archives-count">1</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/%E6%BA%90%E7%A0%81/" rel="tag">源码<span class="mdui-ripple sidebar_archives-count">3</span></a><a class="mdui-ripple sidebar_archives-link" href="/tags/%E7%94%9F%E6%B4%BB%E6%84%9F%E6%82%9F/" rel="tag">生活感悟<span class="mdui-ripple sidebar_archives-count">1</span></a>
        
      </div>
    </div>
    <a href="/about" class="mdui-list-item mdui-ripple">
      <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-purple">person</i>
      <div class="mdui-list-item-content">关于</div>
    </a>
  </div>

  <div class="mdui-divider"></div>

  <div class="mdui-list" mdui-collapse="{accordion: true}">
    
      <a href="/timeline" class="mdui-list-item mdui-ripple">时间轴</a>
    
    <div class="mdui-collapse-item">
      <script>var a=localStorage.getItem("mdui-collapse-item-3");if(a){document.getElementsByClassName("mdui-collapse-item")[3].className+=" mdui-collapse-item-open"};</script>
      <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
        <div class="mdui-list-item-content">友情链接</div>
        <i class="mdui-list-item-icon mdui-icon material-icons">link</i>
      </div>
      <div class="mdui-collapse-item-body mdui-list mdui-list-dense">
        
          <a href="http://www.niemingzhao.top" target="_blank" class="mdui-list-item mdui-p-l-2 mdui-text-color-theme-accent mdui-ripple" style="justify-content: center;">聂明照的博客</a>
        
        
      </div>
    </div>
  </div>
</aside>

  <main id="main" class="mdui-m-t-5 fadeIn animated">
  
<link rel="stylesheet" href="//cdn.bootcdn.net/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  <style>#main article .mdui-card-content .center-block{display:block!important;margin-right:auto!important;margin-left:auto!important}</style>
  <style>#main article .mdui-card-content .text-center{text-align:center!important}</style>
  <article class="mdui-card mdui-m-b-5">
    <header class="mdui-card-media">
      <img src="/images/random/material-14.png" style="max-height: 240px;">
      <div class="mdui-card-media-covered">
        <div class="mdui-card-primary">
          <div class="mdui-card-primary-title">Android 10.0 Launcher 启动流程</div>
          <div class="mdui-card-primary-subtitle"><i class="iconfont">&#xe697;</i> 2023-11-25 / <i class="iconfont">&#xe601;</i> 龙之叶 &nbsp;&nbsp; <span id="busuanzi_container_page_pv" style="display: none;"><i class="iconfont">&#xe7fd;</i> <span id="busuanzi_value_page_pv"></span></span></div>
        </div>
      </div>
      <div class="mdui-card-menu">
        
          <button class="mdui-btn mdui-btn-icon mdui-text-color-white" mdui-menu="{target: '#qrcode', align: 'right'}"><i class="mdui-icon material-icons">devices</i></button>
          <ul class="mdui-menu" id="qrcode">
            
              <li class="mdui-menu-item"><a class="mdui-text-center mdui-ripple">发送到手机</a></li>
            
            <li class="mdui-menu-item" disabled>
              
                <img src="//qr.liantu.com/api.php?w=246&m=10&text=http://longzhiye.top/2023/11/25/2023-11-25/">
              
            </li>
          </ul>
        
        
          <button class="mdui-btn mdui-btn-icon mdui-text-color-white" mdui-menu="{target: '#share_menu', align: 'right'}"><i class="mdui-icon material-icons">share</i></button>
          <ul class="mdui-menu" id="share_menu">
            <li class="mdui-menu-item">
              <a href="https://service.weibo.com/share/share.php?appkey=&title=Android 10.0 Launcher 启动流程&url=http://longzhiye.top/2023/11/25/2023-11-25/&pic=http://longzhiye.top/images/favicon.png&searchPic=false&style=simple" target="_blank" class="mdui-ripple">分享到 Weibo</a>
            </li>
            <li class="mdui-menu-item">
              <a href="https://twitter.com/intent/tweet?text=Android 10.0 Launcher 启动流程&url=http://longzhiye.top/2023/11/25/2023-11-25/&via=龙之叶" target="_blank" class="mdui-ripple">分享到 Twitter</a>
            </li>
            <li class="mdui-menu-item">
              <a href="https://www.facebook.com/sharer/sharer.php?u=http://longzhiye.top/2023/11/25/2023-11-25/" target="_blank" class="mdui-ripple">分享到 Facebook</a>
            </li>
            <li class="mdui-menu-item">
              <a href="https://plus.google.com/share?url=http://longzhiye.top/2023/11/25/2023-11-25/" target="_blank" class="mdui-ripple">分享到 Google+</a>
            </li>
            <li class="mdui-menu-item">
              <a href="https://www.linkedin.com/shareArticle?mini=true&url=http://longzhiye.top/2023/11/25/2023-11-25/&title=Android 10.0 Launcher 启动流程" target="_blank" class="mdui-ripple">分享到 LinkedIn</a>
            </li>
            <li class="mdui-menu-item">
              <a href="https://connect.qq.com/widget/shareqq/index.html?site=龙之叶的博客&title=Android 10.0 Launcher 启动流程&pics=http://longzhiye.top/images/favicon.png&url=http://longzhiye.top/2023/11/25/2023-11-25/" target="_blank" class="mdui-ripple">分享到 QQ</a>
            </li>
            <li class="mdui-menu-item">
              <a href="https://telegram.me/share/url?url=http://longzhiye.top/2023/11/25/2023-11-25/&text=Android 10.0 Launcher 启动流程" target="_blank" class="mdui-ripple">分享到 Telegram</a>
            </li>
          </ul>
        
      </div>
    </header>
    <div class="mdui-card-content mdui-typo">
      <p>在前面SystemUI启动流程中说到，在SystemServer中会去启动各种系统服务，这里的launcher也是启动的其中一个服务ActivityManagerService去启动的。在android10之前，系统四大组件的启动都是在ActivityManagerService中，在android10中，单独抽出了一个ActivityTaskManagerService，主要负责Activity的管理和调度。这里先来看下ActivityManagerService服务的启动：<br><strong>frameworks/base/services/java/com/android/server/SystemServer.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">startBootstrapServices</span><span class="params">()</span> &#123;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">// Activity manager runs the show.</span></span><br><span class="line">    traceBeginAndSlog(<span class="string">&quot;StartActivityManager&quot;</span>);</span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span> Might need to move after migration to WM.</span></span><br><span class="line">    <span class="type">ActivityTaskManagerService</span> <span class="variable">atm</span> <span class="operator">=</span> mSystemServiceManager.startService(</span><br><span class="line">            ActivityTaskManagerService.Lifecycle.class).getService();</span><br><span class="line">    mActivityManagerService = ActivityManagerService.Lifecycle.startService(</span><br><span class="line">            mSystemServiceManager, atm);</span><br><span class="line">    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);</span><br><span class="line">    mActivityManagerService.setInstaller(installer);</span><br><span class="line">    mWindowManagerGlobalLock = atm.getGlobalLock();</span><br><span class="line">    traceEnd();</span><br><span class="line">    ... ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当SystemServiceManager调用 startService() 时，就会通过反射去创建传进去的class，然后在调用创建对象的 onStart() 方法，这里就是去初始化ActivityTaskManagerService和ActivityManagerService对象，并不会去启动launcher，而且系统服务启动分为三块：<br><strong>frameworks/base/services/java/com/android/server/SystemServer.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">startBootstrapServices();   <span class="comment">// 启动引导服务</span></span><br><span class="line">startCoreServices();        <span class="comment">// 启动核心服务</span></span><br><span class="line">startOtherServices();       <span class="comment">// 启动其他服务</span></span><br></pre></td></tr></table></figure>
<p>在startOtherServices（）中可以看到：<br><strong>frameworks/base/services/java/com/android/server/SystemServer.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">startOtherServices</span><span class="params">()</span> &#123;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">// We now tell the activity manager it is okay to run third party</span></span><br><span class="line">    <span class="comment">// code.  It will call back into us once it has gotten to the state</span></span><br><span class="line">    <span class="comment">// where third party code can really run (but before it has actually</span></span><br><span class="line">    <span class="comment">// started launching the initial applications), for us to complete our</span></span><br><span class="line">    <span class="comment">// initialization.</span></span><br><span class="line">    mActivityManagerService.systemReady(() -&gt; &#123;</span><br><span class="line">        ... ...</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这就说明在所有服务初始化完成后，在这里会通知ActivityManagerService的systemReady()启动 launcher 的进程。<br>下面一起来看 launcher 是如何被启动起来的：<br><strong>frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">systemReady</span><span class="params">(<span class="keyword">final</span> Runnable goingCallback, TimingsTraceLog traceLog)</span> &#123;</span><br><span class="line">    ... ...</span><br><span class="line">    mAtmInternal.startHomeOnAllDisplays(currentUserId, <span class="string">&quot;systemReady&quot;</span>);</span><br><span class="line">    ... ...</span><br><span class="line">    mAtmInternal.resumeTopActivities(<span class="literal">false</span> <span class="comment">/* scheduleIdle */</span>);</span><br><span class="line">    ... ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>mAtmInternal类型是ActivityTaskManagerInternal，这是一个抽象类，其实现是ActivityTaskManagerService的内部类LocalService：<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">LocalService</span> <span class="keyword">extends</span> <span class="title class_">ActivityTaskManagerInternal</span> &#123;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">startHomeOnAllDisplays</span><span class="params">(<span class="type">int</span> userId, String reason)</span> &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (mGlobalLock) &#123;</span><br><span class="line">            <span class="keyword">return</span> mRootActivityContainer.startHomeOnAllDisplays(userId, reason);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ... ...</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">resumeTopActivities</span><span class="params">(<span class="type">boolean</span> scheduleIdle)</span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (mGlobalLock)&#123;</span><br><span class="line">            mRootActivityContainer.resumeFocusedStacksTopActivities();</span><br><span class="line">            <span class="keyword">if</span>(scheduleIdle)&#123;</span><br><span class="line">                mStackSupervisor.scheduleIdleLocked();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ... ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里的mRootActivityContainer类型是RootActivityContainer，按照文档上的说明，这是一个临时类，主要是将ActivityStackSupervisor.java中的一部分逻辑分离出来，在android11中，这个类就已经找不到了。替换成了RootWindowContainer，这里我们跟进 mRootActivityContainer.startHomeOnAllDisplays() 方法看，最终会调用到：startHomeOnDisplay() :<br><strong>frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">boolean</span> <span class="title function_">startHomeOnDisplay</span><span class="params">(<span class="type">int</span> userId,String reason,<span class="type">int</span> displayId,<span class="type">boolean</span> allowInstrumenting,<span class="type">boolean</span> fromHomeKey)</span>&#123;</span><br><span class="line">    <span class="comment">// Fallback to top focused display if the displayId is invalid.</span></span><br><span class="line">    <span class="keyword">if</span>(displayId==INVALID_DISPLAY)&#123;</span><br><span class="line">        displayId=getTopDisplayFocusedStack().mDisplayId;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    Intent homeIntent=<span class="literal">null</span>;</span><br><span class="line">    ActivityInfo aInfo=<span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">if</span>(displayId==DEFAULT_DISPLAY)&#123;</span><br><span class="line">        <span class="comment">//拿到需要启动launcher的intent，通过resolveHomeActivity解析出需要启动的Activity</span></span><br><span class="line">        homeIntent=mService.getHomeIntent();</span><br><span class="line">        aInfo=resolveHomeActivity(userId,homeIntent);</span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(shouldPlaceSecondaryHomeOnDisplay(displayId))&#123;</span><br><span class="line">        Pair&lt;ActivityInfo, Intent&gt; info=resolveSecondaryHomeActivity(userId,displayId);</span><br><span class="line">        aInfo=info.first;</span><br><span class="line">        homeIntent=info.second;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(aInfo==<span class="literal">null</span>||homeIntent==<span class="literal">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">if</span>(!canStartHomeOnDisplay(aInfo,displayId,allowInstrumenting))&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="comment">// Updates the home component of the intent.</span></span><br><span class="line">    homeIntent.setComponent(<span class="keyword">new</span> <span class="title class_">ComponentName</span>(aInfo.applicationInfo.packageName,aInfo.name));</span><br><span class="line">    homeIntent.setFlags(homeIntent.getFlags()|FLAG_ACTIVITY_NEW_TASK);</span><br><span class="line">    <span class="comment">// Updates the extra information of the intent.</span></span><br><span class="line">    <span class="keyword">if</span>(fromHomeKey)&#123;</span><br><span class="line">        homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY,<span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Update the reason for ANR debugging to verify if the user activity is the one that</span></span><br><span class="line">    <span class="comment">// actually launched.</span></span><br><span class="line">    <span class="keyword">final</span> String myReason=reason+<span class="string">&quot;:&quot;</span>+userId+<span class="string">&quot;:&quot;</span>+UserHandle.getUserId(</span><br><span class="line">    aInfo.applicationInfo.uid)+<span class="string">&quot;:&quot;</span>+displayId;</span><br><span class="line">    mService.getActivityStartController().startHomeActivity(homeIntent,aInfo,myReason,</span><br><span class="line">    displayId);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里可以分为两步看：<br>  1、通过ActivityTaskManagerService的getHomeIntent（）获取到需要启动的intent，在通过resolveHomeActivity（）解析出需要启动Activity的信息，<br>  2、mService.getActivityStartController()获取到的是ActivityStartController，这个类的主要作用是用于控制委派启动的Activity。<br>先来看下ActivityTaskManagerService的getHomeIntent() :<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Intent <span class="title function_">getHomeIntent</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">Intent</span> <span class="variable">intent</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Intent</span>(mTopAction, mTopData != <span class="literal">null</span> ? Uri.parse(mTopData) : <span class="literal">null</span>);</span><br><span class="line">    intent.setComponent(mTopComponent);</span><br><span class="line">    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);</span><br><span class="line">    <span class="keyword">if</span> (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) &#123;</span><br><span class="line">        intent.addCategory(Intent.CATEGORY_HOME);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> intent;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意看 intent.addCategory(Intent.CATEGORY_HOME) ，这个代表的就是要启动Activity的意图，通常来说，整个系统的只会有一个应用会在清单文件中配置CATEGORY_HOME，如果配置了多个，系统在启动的时候就会要求用户手动去选择哪个作为启动应用，如果在系统设置应用中进行配置了，就会选择配置的那个应用启动。（这个 CATEGORY_HOME 配置，说白了就只有 launcher 程序才会有）。<br>回到主线，接着看mService.getActivityStartController().startHomeActivity() :<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">startHomeActivity</span><span class="params">(Intent intent, ActivityInfo aInfo, String reason,</span></span><br><span class="line"><span class="params">        TaskDisplayArea taskDisplayArea)</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="type">ActivityOptions</span> <span class="variable">options</span> <span class="operator">=</span> ActivityOptions.makeBasic();</span><br><span class="line">    options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);</span><br><span class="line">    <span class="keyword">if</span> (!ActivityRecord.isResolverActivity(aInfo.name)) &#123;</span><br><span class="line">        <span class="comment">// The resolver activity shouldn&#x27;t be put in home stack because when the foreground is</span></span><br><span class="line">        <span class="comment">// standard type activity, the resolver activity should be put on the top of current</span></span><br><span class="line">        <span class="comment">// foreground instead of bring home stack to front.</span></span><br><span class="line">        options.setLaunchActivityType(ACTIVITY_TYPE_HOME);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">final</span> <span class="type">int</span> <span class="variable">displayId</span> <span class="operator">=</span> taskDisplayArea.getDisplayId();</span><br><span class="line">    options.setLaunchDisplayId(displayId);</span><br><span class="line">    options.setLaunchTaskDisplayArea(taskDisplayArea.mRemoteToken</span><br><span class="line">            .toWindowContainerToken());</span><br><span class="line">    <span class="comment">// The home activity will be started later, defer resuming to avoid unneccerary operations</span></span><br><span class="line">    <span class="comment">// (e.g. start home recursively) when creating home stack.</span></span><br><span class="line">    mSupervisor.beginDeferResume();</span><br><span class="line">    <span class="keyword">final</span> ActivityStack homeStack;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// Make sure home stack exists on display area.</span></span><br><span class="line">        homeStack = taskDisplayArea.getOrCreateRootHomeTask(ON_TOP);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        mSupervisor.endDeferResume();</span><br><span class="line">    &#125;</span><br><span class="line">    mLastHomeActivityStartResult = obtainStarter(intent, <span class="string">&quot;startHomeActivity: &quot;</span> + reason)</span><br><span class="line">            .setOutActivity(tmpOutRecord)</span><br><span class="line">            .setCallingUid(<span class="number">0</span>)</span><br><span class="line">            .setActivityInfo(aInfo)</span><br><span class="line">            .setActivityOptions(options.toBundle())</span><br><span class="line">            .execute();</span><br><span class="line">    mLastHomeActivityStartRecord = tmpOutRecord[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">if</span> (homeStack.mInResumeTopActivity) &#123;</span><br><span class="line">        <span class="comment">// If we are in resume section already, home activity will be initialized, but not</span></span><br><span class="line">        <span class="comment">// resumed (to avoid recursive resume) and will stay that way until something pokes it</span></span><br><span class="line">        <span class="comment">// again. We need to schedule another resume.</span></span><br><span class="line">        mSupervisor.scheduleResumeTopActivities();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> A starter to configure and execute starting an activity. It is valid until after</span></span><br><span class="line"><span class="comment"> *         &#123;<span class="doctag">@link</span> ActivityStarter#execute&#125; is invoked. At that point, the starter should be</span></span><br><span class="line"><span class="comment"> *         considered invalid and no longer modified or used.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">ActivityStarter <span class="title function_">obtainStarter</span><span class="params">(Intent intent, String reason)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> mFactory.obtain().setIntent(intent).setReason(reason);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里主要是先获取一个ActivityStarter（主要用于启动Activity），然后把需要的参数设置进去，最后再调用它的ActivityStarter.execute（）方法：<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">execute</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        ... ...</span><br><span class="line">        <span class="keyword">final</span> LaunchingState launchingState;</span><br><span class="line">        <span class="keyword">synchronized</span> (mService.mGlobalLock) &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="type">ActivityRecord</span> <span class="variable">caller</span> <span class="operator">=</span> ActivityRecord.forTokenLocked(mRequest.resultTo);</span><br><span class="line">            <span class="comment">// 通过ActivityMetricsLogger.notifyActivityLaunching创建LaunchingState并记录创建Activity开始的时间</span></span><br><span class="line">            launchingState = mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(</span><br><span class="line">                    mRequest.intent, caller);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        ... ...</span><br><span class="line">        <span class="comment">// 执行启动请求</span></span><br><span class="line">        res = executeRequest(mRequest);</span><br><span class="line">        ... ...</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// Notify ActivityMetricsLogger that the activity has launched.</span></span><br><span class="line">        <span class="comment">// ActivityMetricsLogger will then wait for the windows to be drawn and populate</span></span><br><span class="line">        <span class="comment">// WaitResult.</span></span><br><span class="line">        <span class="comment">// 通过ActivityMetricsLogger.notifyActivityLaunched记录Activity启动完成的时间</span></span><br><span class="line">        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, res,</span><br><span class="line">                mLastStartActivityRecord);</span><br><span class="line">        <span class="comment">// 同时将Request.waitResult添加到ActivityStackSupervisor的mWaitingActivityLaunched中，等待窗口绘制完成</span></span><br><span class="line">        <span class="keyword">return</span> getExternalResult(mRequest.waitResult == <span class="literal">null</span> ? res</span><br><span class="line">                : waitForResult(res, mLastStartActivityRecord));        </span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            onExecutionComplete();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>通过上面代码我们知道，启动是在 executeRequest() 方法里：<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="type">int</span> <span class="title function_">executeRequest</span><span class="params">(Request request)</span> &#123;</span><br><span class="line">... ...</span><br><span class="line">    <span class="comment">//调用 startActivityUnchecked</span></span><br><span class="line">    mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,</span><br><span class="line">            request.voiceInteractor, startFlags, <span class="literal">true</span> <span class="comment">/* doResume */</span>, checkedOptions, inTask,</span><br><span class="line">            restrictedBgActivity, intentGrants);</span><br><span class="line">    <span class="keyword">return</span> mLastStartActivityResult;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ActivityStarter.startActivityUnchecked()<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="type">int</span> <span class="title function_">startActivityUnchecked</span><span class="params">(<span class="keyword">final</span> ActivityRecord r, ActivityRecord sourceRecord,</span></span><br><span class="line"><span class="params">            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,</span></span><br><span class="line"><span class="params">            <span class="type">int</span> startFlags, <span class="type">boolean</span> doResume, ActivityOptions options, Task inTask,</span></span><br><span class="line"><span class="params">            <span class="type">boolean</span> restrictedBgActivity, NeededUriGrants intentGrants)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">result</span> <span class="operator">=</span> START_CANCELED;</span><br><span class="line">  ... ...</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//延时布局</span></span><br><span class="line">        mService.deferWindowLayout();</span><br><span class="line">        <span class="comment">//执行startActivityInner</span></span><br><span class="line">        result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,</span><br><span class="line">                startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">//恢复布局</span></span><br><span class="line">        mService.continueWindowLayout();</span><br><span class="line">    &#125;</span><br><span class="line">  ... ...</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ActivityStarter.startActivityInner()<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">startActivityInner</span><span class="params">()</span> &#123; </span><br><span class="line">    ... ...</span><br><span class="line">       <span class="keyword">if</span> (mDoResume) &#123;</span><br><span class="line">            <span class="comment">//ActivityRecord 记录着 Activity 信息</span></span><br><span class="line">            <span class="keyword">final</span> <span class="type">ActivityRecord</span> <span class="variable">topTaskActivity</span> <span class="operator">=</span></span><br><span class="line">                    mStartActivity.getTask().topRunningActivityLocked();</span><br><span class="line">            <span class="keyword">if</span> (!mTargetStack.isTopActivityFocusable()</span><br><span class="line">                    || (topTaskActivity != <span class="literal">null</span> &amp;&amp; topTaskActivity.isTaskOverlay()</span><br><span class="line">                    &amp;&amp; mStartActivity != topTaskActivity)) &#123;</span><br><span class="line">                mTargetStack.getDisplay().mDisplayContent.executeAppTransition();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//执行resumeFocusedStacksTopActivities</span></span><br><span class="line">                mRootWindowContainer.resumeFocusedStacksTopActivities(</span><br><span class="line">                        mTargetStack, mStartActivity, mOptions);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    ... ...</span><br><span class="line">        <span class="keyword">return</span> START_SUCCESS;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>RootWindowContainer.resumeFocusedStacksTopActivities()<br><strong>frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">boolean</span> <span class="title function_">resumeFocusedStacksTopActivities</span><span class="params">(</span></span><br><span class="line"><span class="params">            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions)</span> &#123;</span><br><span class="line">    ... ...</span><br><span class="line">        <span class="comment">//如果是栈顶Activity，启动resumeTopActivityUncheckedLocked</span></span><br><span class="line">        <span class="keyword">if</span> (targetStack != <span class="literal">null</span> &amp;&amp; (targetStack.isTopStackInDisplayArea()</span><br><span class="line">                || getTopDisplayFocusedStack() == targetStack)) &#123;</span><br><span class="line">            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);</span><br><span class="line">        &#125;</span><br><span class="line">    ... ...</span><br><span class="line">        <span class="keyword">if</span> (!resumedOnDisplay) &#123;</span><br><span class="line">            <span class="comment">//获取栈顶的 ActivityRecord</span></span><br><span class="line">            <span class="keyword">final</span> <span class="type">ActivityStack</span> <span class="variable">focusedStack</span> <span class="operator">=</span> display.getFocusedStack();</span><br><span class="line">            <span class="keyword">if</span> (focusedStack != <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="comment">//执行resumeTopActivityUncheckedLocked</span></span><br><span class="line">                result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);</span><br><span class="line">            &#125;<span class="keyword">else</span> <span class="keyword">if</span> (targetStack == <span class="literal">null</span>) &#123;</span><br><span class="line">                    result |= resumeHomeActivity(<span class="literal">null</span> <span class="comment">/* prev */</span>, <span class="string">&quot;no-focusable-task&quot;</span>,</span><br><span class="line">                            display.getDefaultTaskDisplayArea());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ActivityStack.resumeTopActivityUncheckedLocked()<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">boolean</span> <span class="title function_">resumeTopActivityUncheckedLocked</span><span class="params">(ActivityRecord prev, ActivityOptions options)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (mInResumeTopActivity) &#123;</span><br><span class="line">        <span class="comment">// Don&#x27;t even start recursing.</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">boolean</span> <span class="variable">result</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        mInResumeTopActivity = <span class="literal">true</span>;</span><br><span class="line">        <span class="comment">// 执行 resumeTopActivityInnerLocked,</span></span><br><span class="line">        <span class="comment">// 最终调用到 ActivityStackSupervisor.startSpecificActivity()</span></span><br><span class="line">        result = resumeTopActivityInnerLocked(prev, options);</span><br><span class="line">        <span class="keyword">final</span> <span class="type">ActivityRecord</span> <span class="variable">next</span> <span class="operator">=</span> topRunningActivity(<span class="literal">true</span> <span class="comment">/* focusableOnly */</span>);</span><br><span class="line">        <span class="keyword">if</span> (next == <span class="literal">null</span> || !next.canTurnScreenOn()) &#123;</span><br><span class="line">            checkReadyForSleep();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        mInResumeTopActivity = <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ActivityStackSupervisor.startSpecificActivity()<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">startSpecificActivity</span><span class="params">(ActivityRecord r, <span class="type">boolean</span> andResume, <span class="type">boolean</span> checkConfig)</span> &#123;</span><br><span class="line">    <span class="comment">// Is this activity&#x27;s application already running?</span></span><br><span class="line">    <span class="keyword">final</span> <span class="type">WindowProcessController</span> <span class="variable">wpc</span> <span class="operator">=</span></span><br><span class="line">            mService.getProcessController(r.processName, r.info.applicationInfo.uid);</span><br><span class="line"> </span><br><span class="line">    <span class="type">boolean</span> <span class="variable">knownToBeDead</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="comment">//进程存在</span></span><br><span class="line">    <span class="keyword">if</span> (wpc != <span class="literal">null</span> &amp;&amp; wpc.hasThread()) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//真正启动Activity方法</span></span><br><span class="line">            realStartActivityLocked(r, wpc, andResume, checkConfig);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RemoteException e) &#123;</span><br><span class="line">            Slog.w(TAG, <span class="string">&quot;Exception when starting activity &quot;</span></span><br><span class="line">                    + r.intent.getComponent().flattenToShortString(), e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// If a dead object exception was thrown -- fall through to</span></span><br><span class="line">        <span class="comment">// restart the application.</span></span><br><span class="line">        knownToBeDead = <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    r.notifyUnknownVisibilityLaunchedForKeyguardTransition();</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">final</span> <span class="type">boolean</span> <span class="variable">isTop</span> <span class="operator">=</span> andResume &amp;&amp; r.isTopRunningActivity();</span><br><span class="line">    <span class="comment">//进程不存在 mService =ATMS</span></span><br><span class="line">    mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? <span class="string">&quot;top-activity&quot;</span> : <span class="string">&quot;activity&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>startSpecificActivity() 这个方法是关键方法，如果进程已经存在直接执行 realStartActivityLocked 去启动 Activity，进程不存在则通过AMS去创建 Socket，然后通知 Zygote 去 fork 进程。由于这里第一次创建，所以会走到 startProcessAsync() 。<br>Launcher启动流程调用栈：<br><img src="/images/20231125/20231125001.jpg"></p>
<p>创建Socket建立连接<br>ActivityTaskManagerService.startProcessAsync()<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">startProcessAsync</span><span class="params">(ActivityRecord activity, <span class="type">boolean</span> knownToBeDead, <span class="type">boolean</span> isTop,</span></span><br><span class="line"><span class="params">        String hostingType)</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) &#123;</span><br><span class="line">            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, <span class="string">&quot;dispatchingStartProcess:&quot;</span></span><br><span class="line">                    + activity.processName);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Post message to start process to avoid possible deadlock of calling into AMS with the</span></span><br><span class="line">        <span class="comment">// ATMS lock held.</span></span><br><span class="line">        <span class="keyword">final</span> <span class="type">Message</span> <span class="variable">m</span> <span class="operator">=</span> PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,</span><br><span class="line">                mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,</span><br><span class="line">                isTop, hostingType, activity.intent.getComponent());</span><br><span class="line">        mH.sendMessage(m);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过handler发消息执行ActivityManagerInternal.startProcess() ，内部又转调用ActivityManagerService.startProcessLocked() :<br><strong>frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GuardedBy(&quot;this&quot;)</span></span><br><span class="line"><span class="keyword">final</span> ProcessRecord <span class="title function_">startProcessLocked</span><span class="params">(String processName,</span></span><br><span class="line"><span class="params">        ApplicationInfo info, <span class="type">boolean</span> knownToBeDead, <span class="type">int</span> intentFlags,</span></span><br><span class="line"><span class="params">        HostingRecord hostingRecord, <span class="type">int</span> zygotePolicyFlags, <span class="type">boolean</span> allowWhileBooting,</span></span><br><span class="line"><span class="params">        <span class="type">boolean</span> isolated, <span class="type">boolean</span> keepIfLarge)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,</span><br><span class="line">            hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, <span class="number">0</span> <span class="comment">/* isolatedUid */</span>,</span><br><span class="line">            keepIfLarge, <span class="literal">null</span> <span class="comment">/* ABI override */</span>, <span class="literal">null</span> <span class="comment">/* entryPoint */</span>,</span><br><span class="line">            <span class="literal">null</span> <span class="comment">/* entryPointArgs */</span>, <span class="literal">null</span> <span class="comment">/* crashHandler */</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>mProcessList类型是ProcessList，这是一个进程管理类，描述了进程的adj值，当系统资源吃紧时，就会根据这里描述的adj去判断杀死哪个应用来释放资源，可以通过adb shell dumpsys meminfo来查看当前所有进程的分类情况，接着来看下ProcessList.startProcessLocked():<br><strong>frameworks/base/services/core/java/com/android/server/am/ProcessList.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> ProcessRecord <span class="title function_">startProcessLocked</span><span class="params">(String processName, ApplicationInfo info,</span></span><br><span class="line"><span class="params">        <span class="type">boolean</span> knownToBeDead, <span class="type">int</span> intentFlags, HostingRecord hostingRecord,</span></span><br><span class="line"><span class="params">        <span class="type">boolean</span> allowWhileBooting, <span class="type">boolean</span> isolated, <span class="type">int</span> isolatedUid, <span class="type">boolean</span> keepIfLarge,</span></span><br><span class="line"><span class="params">        String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    ProcessRecord app;</span><br><span class="line">    ... ...</span><br><span class="line">    checkSlow(startTime, <span class="string">&quot;startProcess: stepping in to startProcess&quot;</span>);</span><br><span class="line">    <span class="keyword">final</span> <span class="type">boolean</span> <span class="variable">success</span> <span class="operator">=</span> startProcessLocked(app, hostingRecord, abiOverride);</span><br><span class="line">    checkSlow(startTime, <span class="string">&quot;startProcess: done starting proc!&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> success ? app : <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="type">boolean</span> <span class="title function_">startProcessLocked</span><span class="params">(ProcessRecord app, HostingRecord hostingRecord,</span></span><br><span class="line"><span class="params">        <span class="type">boolean</span> disableHiddenApiChecks, <span class="type">boolean</span> mountExtStorageFull,</span></span><br><span class="line"><span class="params">        String abiOverride)</span> &#123;</span><br><span class="line">        ... ...</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        ... ...</span><br><span class="line">        <span class="comment">// Start the process.  It will either succeed and return a result containing</span></span><br><span class="line">        <span class="comment">// the PID of the new process, or else throw a RuntimeException.</span></span><br><span class="line">        <span class="keyword">final</span> <span class="type">String</span> <span class="variable">entryPoint</span> <span class="operator">=</span> <span class="string">&quot;android.app.ActivityThread&quot;</span>;</span><br><span class="line"> </span><br><span class="line">        <span class="keyword">return</span> startProcessLocked(hostingRecord, entryPoint, app, uid, gids,</span><br><span class="line">                runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,</span><br><span class="line">                startTime);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (RuntimeException e) &#123;</span><br><span class="line">        Slog.e(ActivityManagerService.TAG, <span class="string">&quot;Failure starting process &quot;</span> + app.processName, e);</span><br><span class="line"> </span><br><span class="line">        <span class="comment">// Something went very wrong while trying to start this process; one</span></span><br><span class="line">        <span class="comment">// common case is when the package is frozen due to an active</span></span><br><span class="line">        <span class="comment">// upgrade. To recover, clean up any active bookkeeping related to</span></span><br><span class="line">        <span class="comment">// starting this process. (We already invoked this method once when</span></span><br><span class="line">        <span class="comment">// the package was initially frozen through KILL_APPLICATION_MSG, so</span></span><br><span class="line">        <span class="comment">// it doesn&#x27;t hurt to use it again.)</span></span><br><span class="line">        mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),</span><br><span class="line">                <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, app.userId, <span class="string">&quot;start failure&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="type">boolean</span> <span class="title function_">startProcessLocked</span><span class="params">(HostingRecord hostingRecord,String entryPoint,</span></span><br><span class="line"><span class="params">        ProcessRecord app, <span class="type">int</span> uid, <span class="type">int</span>[] gids, <span class="type">int</span> runtimeFlags, <span class="type">int</span> mountExternal,</span></span><br><span class="line"><span class="params">        String seInfo, String requiredAbi, String instructionSet, String invokeWith,<span class="type">long</span> startTime)</span> &#123;</span><br><span class="line">        ... ...</span><br><span class="line">        <span class="keyword">final</span> Process.<span class="type">ProcessStartResult</span> <span class="variable">startResult</span> <span class="operator">=</span> startProcess(app.hostingRecord,entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);</span><br><span class="line">        ... ...</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">private</span> Process.ProcessStartResult <span class="title function_">startProcess</span><span class="params">(HostingRecord hostingRecord, String entryPoint,</span></span><br><span class="line"><span class="params">        ProcessRecord app, <span class="type">int</span> uid, <span class="type">int</span>[] gids, <span class="type">int</span> runtimeFlags, <span class="type">int</span> mountExternal,</span></span><br><span class="line"><span class="params">        String seInfo, String requiredAbi, String instructionSet, String invokeWith,</span></span><br><span class="line"><span class="params">        <span class="type">long</span> startTime)</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, <span class="string">&quot;Start proc: &quot;</span> +</span><br><span class="line">                app.processName);</span><br><span class="line">        checkSlow(startTime, <span class="string">&quot;startProcess: asking zygote to start proc&quot;</span>);</span><br><span class="line">        <span class="keyword">final</span> Process.ProcessStartResult startResult;</span><br><span class="line">        <span class="keyword">if</span> (hostingRecord.usesWebviewZygote()) &#123;</span><br><span class="line">            ... ...</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (hostingRecord.usesAppZygote()) &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="type">AppZygote</span> <span class="variable">appZygote</span> <span class="operator">=</span> createAppZygoteForProcessIfNeeded(app);</span><br><span class="line"> </span><br><span class="line">            startResult = appZygote.getProcess().start(entryPoint,</span><br><span class="line">                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,</span><br><span class="line">                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,</span><br><span class="line">                    app.info.dataDir, <span class="literal">null</span>, app.info.packageName,</span><br><span class="line">                    <span class="comment">/*useUsapPool=*/</span> <span class="literal">false</span>,</span><br><span class="line">                    <span class="keyword">new</span> <span class="title class_">String</span>[] &#123;PROC_START_SEQ_IDENT + app.startSeq&#125;);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ... ...</span><br><span class="line">        &#125;</span><br><span class="line">        checkSlow(startTime, <span class="string">&quot;startProcess: returned from zygote!&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> startResult;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里有几个我们需要关注的点，一个是第二个方法定义的entryPoint=”android.app.ActivityThread”，这个就是后面创建进程时会通过反射调用到的类，再来看最后一个方法，这里会执行else if语句，也就是执行ZygoteProcess的start（）方法。最终到 ZygoteProcess 的attemptUsapSendArgsAndGetResult 通过 Socket 通信，fork 一个新的 Launcher 进程，调用过程如图：</p>
<p><img src="/images/20231125/20231125002.jpg"></p>
<p>ZygoteProcess.attemptZygoteSendArgsAndGetResult()<br><strong>frameworks/base/core/java/android/os/ZygoteProcess.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> Process.ProcessStartResult <span class="title function_">attemptZygoteSendArgsAndGetResult</span><span class="params">(</span></span><br><span class="line"><span class="params">        ZygoteState zygoteState, String msgStr)</span> <span class="keyword">throws</span> ZygoteStartFailedEx &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">final</span> <span class="type">BufferedWriter</span> <span class="variable">zygoteWriter</span> <span class="operator">=</span> zygoteState.mZygoteOutputWriter;</span><br><span class="line">        <span class="keyword">final</span> <span class="type">DataInputStream</span> <span class="variable">zygoteInputStream</span> <span class="operator">=</span> zygoteState.mZygoteInputStream;</span><br><span class="line"> </span><br><span class="line">        zygoteWriter.write(msgStr);把应用进程的一些参数写给前面连接的zygote进程</span><br><span class="line">        zygoteWriter.flush();<span class="comment">//进入Zygote进程，处于阻塞状态</span></span><br><span class="line">        <span class="comment">//从socket中得到zygote创建的应用pid，赋值给 ProcessStartResult的对象</span></span><br><span class="line">        Process.<span class="type">ProcessStartResult</span> <span class="variable">result</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Process</span>.ProcessStartResult();</span><br><span class="line">        result.pid = zygoteInputStream.readInt();</span><br><span class="line">        result.usingWrapper = zygoteInputStream.readBoolean();</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">        zygoteState.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Zygote进程处理<br>ZygoteInit.main<br><strong>frameworks/base/core/java/com/android/internal/os/ZygoteInit.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String argv[])</span> &#123;</span><br><span class="line">    Runnable caller;</span><br><span class="line">    <span class="keyword">if</span> (startSystemServer) &#123;</span><br><span class="line">        <span class="comment">//Zygote Fork出的第一个进程 SystmeServer</span></span><br><span class="line">        <span class="type">Runnable</span> <span class="variable">r</span> <span class="operator">=</span> forkSystemServer(abiList, zygoteSocketName, zygoteServer);</span><br><span class="line"> </span><br><span class="line">        <span class="keyword">if</span> (r != <span class="literal">null</span>) &#123;</span><br><span class="line">            r.run();</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//循环等待fork出其他的应用进程，比如Launcher</span></span><br><span class="line">    caller = zygoteServer.runSelectLoop(abiList);</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">if</span> (caller != <span class="literal">null</span>) &#123;</span><br><span class="line">        caller.run(); <span class="comment">//执行runSelectLoop返回的Runnable对象，进入子进程</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ZygoteServer.runSelectLoop<br><strong>frameworks/base/core/java/com/android/internal/os/ZygoteServer.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Runnable <span class="title function_">runSelectLoop</span><span class="params">(String abiList)</span> &#123;</span><br><span class="line">    <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">        <span class="type">int</span> pollReturnValue;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//epoll机制 循环</span></span><br><span class="line">                pollReturnValue = Os.poll(pollFDs, pollTimeoutMs);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (ErrnoException ex) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;poll failed&quot;</span>, ex);</span><br><span class="line">            &#125;</span><br><span class="line">            ...</span><br><span class="line">            <span class="comment">//来了消息后，调用processOneCommand()来进行进程的处理</span></span><br><span class="line">            <span class="keyword">final</span> <span class="type">Runnable</span> <span class="variable">command</span> <span class="operator">=</span>  connection.processOneCommand(<span class="built_in">this</span>);</span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ZygoteConnection.processOneCommand<br><strong>frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">Runnable <span class="title function_">processOneCommand</span><span class="params">(ZygoteServer zygoteServer)</span> &#123;</span><br><span class="line">            <span class="comment">//fork进程，得到新进程pid</span></span><br><span class="line">            <span class="comment">//pid=0 表示Zygote  fork子进程成功</span></span><br><span class="line">            <span class="comment">//pid &gt; 0 表示子进程 的真正的PID</span></span><br><span class="line">            pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,</span><br><span class="line">                parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,</span><br><span class="line">                parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,</span><br><span class="line">                parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mIsTopApp,</span><br><span class="line">                parsedArgs.mPkgDataInfoList, parsedArgs.mWhitelistedDataInfoList,</span><br><span class="line">                parsedArgs.mBindMountAppDataDirs, parsedArgs.mBindMountAppStorageDirs);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//fork成功，第一次返回的pid = 0</span></span><br><span class="line">            <span class="keyword">if</span> (pid == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                handleParentProc(pid, serverPipeFd);</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ZygoteConnection.handleChildProc<br>这里主要执行到 ZygoteInit.zygoteInit，zygoteInit 进行一些环境的初始化、启动Binder进程等操作，最终反射执行 ActivityThread.main<br><strong>frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> Runnable <span class="title function_">handleChildProc</span><span class="params">(ZygoteArguments parsedArgs,</span></span><br><span class="line"><span class="params">        FileDescriptor pipeFd, <span class="type">boolean</span> isZygote)</span> &#123;</span><br><span class="line">    closeSocket();</span><br><span class="line">    Zygote.setAppProcessName(parsedArgs, TAG);</span><br><span class="line">        <span class="keyword">if</span> (!isZygote) &#123;</span><br><span class="line">            <span class="comment">//App进程将会调用到这里，最终反射执行ActivityThread.main</span></span><br><span class="line">            <span class="keyword">return</span> ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,</span><br><span class="line">                    parsedArgs.mDisabledCompatChanges,</span><br><span class="line">                    parsedArgs.mRemainingArgs, <span class="literal">null</span> <span class="comment">/* classLoader */</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,</span><br><span class="line">                    parsedArgs.mRemainingArgs, <span class="literal">null</span> <span class="comment">/* classLoader */</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Zygote进程调用栈:</p>
<p><img src="/images/20231125/20231125003.jpg"></p>
<p>ActivityThread中处理<br>Zygote fork出了 Launcher 的进程，并把接下来的 Launcher 启动任务交给了 ActivityThread 来进行，接下来我们就从 ActivityThread.main方法来分析 Launcher 的创建过程。<br><strong>frameworks/base/core/java/android/app/ActivityThread.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, <span class="string">&quot;ActivityThreadMain&quot;</span>);</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">//创建主线程Looper</span></span><br><span class="line">    Looper.prepareMainLooper();</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="type">ActivityThread</span> <span class="variable">thread</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ActivityThread</span>();</span><br><span class="line">    <span class="comment">//执行attach</span></span><br><span class="line">    ... ...</span><br><span class="line">    thread.attach(<span class="literal">false</span>, startSeq);</span><br><span class="line">    <span class="comment">//开启循环</span></span><br><span class="line">    ... ...</span><br><span class="line">    Looper.loop();</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;Main thread loop unexpectedly exited&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里就是android层面划分为一个应用进程的开始，初始化一个looper，也就是android中说的主线程，并开始looper循环，这里调用到了ActivitThread.attach() :<br><strong>frameworks/base/core/java/android/app/ActivityThread.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">attach</span><span class="params">(<span class="type">boolean</span> system, <span class="type">long</span> startSeq)</span> &#123;</span><br><span class="line">    sCurrentActivityThread = <span class="built_in">this</span>;</span><br><span class="line">    mSystemThread = system;</span><br><span class="line">    <span class="keyword">if</span> (!system) &#123;</span><br><span class="line">        ... ...</span><br><span class="line">        <span class="comment">// 这里会拿到ActivityManagerService的代理</span></span><br><span class="line">        <span class="keyword">final</span> <span class="type">IActivityManager</span> <span class="variable">mgr</span> <span class="operator">=</span> ActivityManager.getService();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">//应用的句柄发给AMS，从而使AMS可以管理新进程</span></span><br><span class="line">            mgr.attachApplication(mAppThread, startSeq);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RemoteException ex) &#123;</span><br><span class="line">            <span class="keyword">throw</span> ex.rethrowFromSystemServer();</span><br><span class="line">        &#125;</span><br><span class="line">         ... ...</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 在前面讲Zygote进程的时候，里面创建ActivityThread就会执行到这里</span></span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="comment">//当系统配置发生变更时会执行这个回调</span></span><br><span class="line">    ViewRootImpl.<span class="type">ConfigChangedCallback</span> <span class="variable">configChangedCallback</span></span><br><span class="line">            <span class="operator">=</span> (Configuration globalConfig) -&gt; &#123;</span><br><span class="line">        ... ...</span><br><span class="line">    &#125;;</span><br><span class="line">    ViewRootImpl.addConfigCallback(configChangedCallback);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里会执行if语句里面的内容，mAppThread的类型是ApplicationThread，这个类的主要作用是在ActivityManagerService中回调回ActivityThread中来，mgr是ActivityManagerService的代理，在执行它的ActivityManagerService.attachApplication() 方法：<br><strong>frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">attachApplication</span><span class="params">(IApplicationThread thread, <span class="type">long</span> startSeq)</span> &#123;</span><br><span class="line">    <span class="keyword">synchronized</span> (<span class="built_in">this</span>) &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">callingPid</span> <span class="operator">=</span> Binder.getCallingPid();</span><br><span class="line">        <span class="keyword">final</span> <span class="type">int</span> <span class="variable">callingUid</span> <span class="operator">=</span> Binder.getCallingUid();</span><br><span class="line">        <span class="keyword">final</span> <span class="type">long</span> <span class="variable">origId</span> <span class="operator">=</span> Binder.clearCallingIdentity();</span><br><span class="line">        attachApplicationLocked(thread, callingPid, callingUid, startSeq);</span><br><span class="line">        Binder.restoreCallingIdentity(origId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ActivityManagerService.attachApplicationLocked()<br>调用AMS的 attachApplication()，最终层层调用到 ActivityStackSupervisor 的 realStartActivityLocked，真正准备去启动Activity。<br><strong>frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="type">boolean</span> <span class="title function_">attachApplicationLocked</span><span class="params">(IApplicationThread thread,<span class="type">int</span> pid, <span class="type">int</span> callingUid, <span class="type">long</span> startSeq)</span> &#123;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">//这里会去调用ActivityThrea的bindApplication(),也就是会去创建Application</span></span><br><span class="line">    thread.bindApplication(... ...)</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">//如果当前的Application记录仍然依附到之前的进程中，则清理掉</span></span><br><span class="line">    <span class="keyword">if</span> (app.thread != <span class="literal">null</span>) &#123;</span><br><span class="line">        handleAppDiedLocked(app, <span class="literal">true</span>, <span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">// See if the top visible activity is waiting to run in this process...</span></span><br><span class="line">    <span class="keyword">if</span> (normalMode) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//调用ActivityTaskManagerService的attachApplication()，最终层层调用到ActivityStackSupervisor.java的 realStartActivityLocked()</span></span><br><span class="line">            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            Slog.wtf(TAG, <span class="string">&quot;Exception thrown launching activities in &quot;</span> + app, e);</span><br><span class="line">            badApp = <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ... ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里通过AMS最终会调用到ActivityStackSupervisor.realStartActivityLocked()：<br><strong>frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">boolean</span> <span class="title function_">realStartActivityLocked</span><span class="params">(ActivityRecord r, WindowProcessController proc,</span></span><br><span class="line"><span class="params">        <span class="type">boolean</span> andResume, <span class="type">boolean</span> checkConfig)</span> <span class="keyword">throws</span> RemoteException &#123;</span><br><span class="line">    <span class="comment">//确保所有的Activity执行了onPause才会往下继续执行</span></span><br><span class="line">    <span class="keyword">if</span> (!mRootActivityContainer.allPausedActivitiesComplete()) &#123;</span><br><span class="line">        <span class="comment">// While there are activities pausing we skipping starting any new activities until</span></span><br><span class="line">        <span class="comment">// pauses are complete. <span class="doctag">NOTE:</span> that we also do this for activities that are starting in</span></span><br><span class="line">        <span class="comment">// the paused state because they will first be resumed then paused on the client side.</span></span><br><span class="line">        <span class="keyword">if</span> (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,</span><br><span class="line">                <span class="string">&quot;realStartActivityLocked: Skipping start of r=&quot;</span> + r</span><br><span class="line">                + <span class="string">&quot; some activities pausing...&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    ... ...</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        ... ...</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            ... ...</span><br><span class="line">            <span class="comment">// Create activity launch transaction.</span></span><br><span class="line">            <span class="keyword">final</span> <span class="type">ClientTransaction</span> <span class="variable">clientTransaction</span> <span class="operator">=</span> ClientTransaction.obtain(</span><br><span class="line">                    proc.getThread(), r.appToken);</span><br><span class="line"> </span><br><span class="line">            <span class="keyword">final</span> <span class="type">DisplayContent</span> <span class="variable">dc</span> <span class="operator">=</span> r.getDisplay().mDisplayContent;</span><br><span class="line">            <span class="comment">//在回调序列的末尾添加一条消息</span></span><br><span class="line">            clientTransaction.addCallback(LaunchActivityItem.obtain(... ...));</span><br><span class="line"> </span><br><span class="line">            <span class="comment">// Set desired final state.</span></span><br><span class="line">            <span class="keyword">final</span> ActivityLifecycleItem lifecycleItem;</span><br><span class="line">            <span class="keyword">if</span> (andResume) &#123;</span><br><span class="line">                lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                lifecycleItem = PauseActivityItem.obtain();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//添加最后执行的生命周期状态</span></span><br><span class="line">            clientTransaction.setLifecycleStateRequest(lifecycleItem);</span><br><span class="line"> </span><br><span class="line">            <span class="comment">// 这里其实就是执行ClientTransaction的schedule()方法</span></span><br><span class="line">            mService.getLifecycleManager().scheduleTransaction(clientTransaction);</span><br><span class="line">            ... ...</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RemoteException e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (r.launchFailed) &#123;</span><br><span class="line">                <span class="comment">// 第二次启动失败，finish activity并放弃启动</span></span><br><span class="line">                Slog.e(TAG, <span class="string">&quot;Second failure launching &quot;</span></span><br><span class="line">                        + r.intent.getComponent().flattenToShortString() + <span class="string">&quot;, giving up&quot;</span>, e);</span><br><span class="line">                proc.appDied();</span><br><span class="line">                stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, <span class="literal">null</span>,</span><br><span class="line">                        <span class="string">&quot;2nd-crash&quot;</span>, <span class="literal">false</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line"> </span><br><span class="line">            <span class="comment">//第一次启动失败，尝试重启进程</span></span><br><span class="line">            r.launchFailed = <span class="literal">true</span>;</span><br><span class="line">            proc.removeActivity(r);</span><br><span class="line">            <span class="keyword">throw</span> e;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        endDeferResume();</span><br><span class="line">    &#125;</span><br><span class="line">    ... ...</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ActivityThread调用栈:<br><img src="/images/20231125/20231125004.jpg"></p>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><p>至此已经走到 realStartActivityLocked，接下来就是 Activity 的启动流程，Activity 启动下篇文章会单独分析。总结一下 Launcher 启动流程，Launcher的启动经过了三个阶段：<br>  1、SystemServer 创建AMS和ATMS，通过 SystemReady 进入 LauncherActivity 的调用<br>  2、Zygote 进程 fork 出 Launcher 进程，通过 Socket 进行通信<br>  3、进入 ActivityThread 的处理，完成 Launcher 的 Acitivty 启动</p>

      
      <blockquote>
        
        <strong>本文链接：</strong><br><a href="http://longzhiye.top/2023/11/25/2023-11-25/">http://longzhiye.top/2023/11/25/2023-11-25/</a>
      </blockquote>
    </div>
    <footer class="mdui-card-actions">
      
        <a class="mdui-ripple article_categories-link" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a>
      
      
        <a class="mdui-ripple article_tags-link" href="/tags/Android/" rel="tag">Android</a><a class="mdui-ripple article_tags-link" href="/tags/Launcher/" rel="tag">Launcher</a><a class="mdui-ripple article_tags-link" href="/tags/framework/" rel="tag">framework</a>
      
    </footer>
    
  </article>
  
<script src="//cdn.bootcdn.net/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.bootcdn.net/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>

  <script>$("#main article .mdui-card-content img.fancybox").on("click",function(e){$.fancybox.open({src:$(this).attr("src")});});</script>


  <nav id="paginator">
    
      <a rel="prev" class="extend prev" href="/2023/11/26/2023-11-26/">
        <button aria-label="prev" class="mdui-btn mdui-btn-raised mdui-btn-icon mdui-color-theme-accent mdui-ripple"><i class="mdui-icon material-icons">arrow_back</i></button>
        <span class="mdui-p-x-3" mdui-tooltip="{content: 'Android 10.0 状态栏系统图标显示分析'}">上一篇</span>
      </a>
    
    <div class="spacer"></div>
    
      <a rel="next" class="extend next" href="/2023/11/19/2023-11-19/">
        <span class="mdui-p-x-3" mdui-tooltip="{content: 'Android 10.0 Settings 加载流程'}">下一篇</span>
        <button aria-label="next" class="mdui-btn mdui-btn-raised mdui-btn-icon mdui-color-theme-accent mdui-ripple"><i class="mdui-icon material-icons">arrow_forward</i></button>
      </a>
    
  </nav>





</main>
  <footer id="footer" class="mdui-m-t-5 mdui-p-y-3 mdui-color-theme">
  <div class="mdui-p-y-0 mdui-text-center">
    
    
    
    
    
    
    
      <a href="http://github.com/longzhiye" target="_blank" class="mdui-btn mdui-btn-icon mdui-text-color-theme-a100"><i class="mdui-icon iconfont">&#xe7ab;</i></a>
    
    
    
      <a href="https://www.zhihu.com/people/long-zhi-xie-61" target="_blank" class="mdui-btn mdui-btn-icon mdui-text-color-theme-a100"><i class="mdui-icon iconfont">&#xe6c0;</i></a>
    
    
    
      <a href="tencent://tencent:////message/?uin=951898105&Menu=yes" target="_blank" class="mdui-btn mdui-btn-icon mdui-text-color-theme-a100"><i class="mdui-icon iconfont">&#xe651;</i></a>
    
    
  </div>
  <div class="mdui-p-y-1 mdui-text-center">
    Copyright &copy; 2022 - 2025 龙之叶<br>
    Powered by <a href="https://hexo.io/" target="_blank" class="mdui-text-color-theme-accent">Hexo</a>
    <br>
      <span id="busuanzi_container_site_pv" style="display: none;"><i class="iconfont">&#xe7fd;</i> <span id="busuanzi_value_site_pv"></span></span> &nbsp;&nbsp;
      <span id="busuanzi_container_site_uv" style="display: none;"><i class="iconfont">&#xe601;</i> <span id="busuanzi_value_site_uv"></span></span>
    
  </div>
</footer>

  <button id="gotop" class="mdui-fab mdui-fab-fixed mdui-fab-hide mdui-color-theme-accent mdui-ripple"><i class="mdui-icon material-icons">arrow_upward</i></button>
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  
<script src="/js/mdui.js"></script>
<script src="/js/script.js"></script>

  
<script src="/custom.js"></script>

</body>
</html>
